/*
//  Copyright © 2014 Allen County Public Library.

  //        ACPL Mobile is free software: This program is distributed and you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.  ACPL Mobile is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY, including without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with ACPL Mobile. If not, see http://www.gnu.org/licenses/.
 * Author: James Harpe
 * 
 * Description: This activity hosts the tabs for the account page.
 */

package us.in.lib.acpl.Mobile_ACPL;

import java.util.HashMap;

import com.google.analytics.tracking.android.EasyTracker;

import us.in.lib.acpl.Mobile_ACPL.context.Mobile_ACPL;
import us.in.lib.acpl.Mobile_ACPL.parents.BaseFragmentActivity;
import us.in.lib.acpl.Mobile_ACPL.ws.AccountInfoHandler;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.TabHost.TabContentFactory;

/**
 * @author mwho
 * 
 */

public class AccountActivity extends BaseFragmentActivity implements
		TabHost.OnTabChangeListener {

	private TabHost mTabHost;
	private HashMap<String, TabInfo> mapTabInfo = new HashMap<String, TabInfo>();
	private TabInfo mLastTab = null;

	private AccountInfoHandler accHandler;

	public AccountInfoHandler getAccHandler() {
		return accHandler;
	}

	/**
	 * (non-Javadoc)
	 * 
	 * @see android.support.v4.app.FragmentActivity#onCreate(android.os.Bundle)
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {

		String nick = this.getSharedPreferences("myPrefs",
				Context.MODE_WORLD_WRITEABLE).getString("nickname", null);
		if (nick == null || nick.equals("")) {
			String user = this.getSharedPreferences("myPrefs",
					Context.MODE_WORLD_WRITEABLE).getString("user", null);
			this.getActionBar().setTitle("  "+user);
		} else {
			this.getActionBar().setTitle("  "+nick);
		}
		super.onCreate(savedInstanceState);
		// Step 1: Inflate layout
		setContentView(R.layout.account);
		// Step 2: Setup TabHost
		initialiseTabHost(savedInstanceState);
		if (savedInstanceState != null) {
			mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab")); // set
																				// the
																				// tab
																				// as
																				// per
																				// the
																				// saved
																				// state
		}
		
		

		accHandler = new AccountInfoHandler(this);
		accHandler.lookupAccountInfo();
	}
	  @Override
	  public void onStart() {
	    super.onStart();
	
	    EasyTracker.getInstance().activityStart(this); // Add this method.
	  }

	  @Override
	  public void onStop() {
	    super.onStop();
	 
	    EasyTracker.getInstance().activityStop(this); // Add this method.
	  }
	public void handleAccountResponse() {
		findViewById(R.id.accountBar).setVisibility(View.GONE);
		AccountCheckoutsFragment checkoutsFrag = (AccountCheckoutsFragment) this
				.getSupportFragmentManager().findFragmentByTag("Tab1");
		if(checkoutsFrag!=null){
			checkoutsFrag.setList();
		}else{
			Toast toast = Toast.makeText(this, "Error. Please try your operation again", Toast.LENGTH_LONG);
			toast.setGravity(Gravity.CENTER, 0, 0);
			toast.show();
		}
		

		AccountHoldsFragment holdsFrag = (AccountHoldsFragment) this
				.getSupportFragmentManager().findFragmentByTag("Tab2");
		if(holdsFrag !=null){
			holdsFrag.setList();
		}else{
			Toast toast = Toast.makeText(this, "Error. Please try your operation again", Toast.LENGTH_LONG);
			toast.setGravity(Gravity.CENTER, 0, 0);
			toast.show();
		}
	

		AccountFinesFragment finesFrag = (AccountFinesFragment) this
				.getSupportFragmentManager().findFragmentByTag("Tab3");
		if(finesFrag!=null){
			finesFrag.setList();
		}else{
			Toast toast = Toast.makeText(this, "Error. Please try your operation again", Toast.LENGTH_LONG);
			toast.setGravity(Gravity.CENTER, 0, 0);
			toast.show();
		}

	}

	/**
	 * (non-Javadoc)
	 * 
	 * @see android.support.v4.app.FragmentActivity#onSaveInstanceState(android.os.Bundle)
	 */
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		outState.putString("tab", mTabHost.getCurrentTabTag()); // save the tab
																// selected
		super.onSaveInstanceState(outState);
	}

	/**
	 * Step 2: Setup TabHost
	 */
	private void initialiseTabHost(Bundle args) {
		mTabHost = (TabHost) findViewById(android.R.id.tabhost);
		mTabHost.setup();
		TabInfo tabInfo = null;
		
		View tabIndicator = LayoutInflater.from(this).inflate(R.layout.apptheme_tab_indicator_holo, mTabHost.getTabWidget(), false);
		TextView title = (TextView) tabIndicator.findViewById(android.R.id.title); 
		title.setText("Checkouts");
		TabSpec spec = this.mTabHost.newTabSpec("Tab1").setIndicator(tabIndicator);
	
		AccountActivity.addTab(this, this.mTabHost, spec,
				
				(tabInfo = new TabInfo("Tab1", AccountCheckoutsFragment.class,
						args)));
		this.mapTabInfo.put(tabInfo.tag, tabInfo);
		
		
		tabIndicator = LayoutInflater.from(this).inflate(R.layout.apptheme_tab_indicator_holo, mTabHost.getTabWidget(), false);
		title = (TextView) tabIndicator.findViewById(android.R.id.title); 
		title.setText("Holds");
		spec = this.mTabHost.newTabSpec("Tab2").setIndicator(tabIndicator);
		
		AccountActivity
				.addTab(this, this.mTabHost, spec, (tabInfo = new TabInfo("Tab2",
						AccountHoldsFragment.class, args)));
		this.mapTabInfo.put(tabInfo.tag, tabInfo);
		
		tabIndicator = LayoutInflater.from(this).inflate(R.layout.apptheme_tab_indicator_holo, mTabHost.getTabWidget(), false);
		title = (TextView) tabIndicator.findViewById(android.R.id.title); 
		title.setText("Fines");
		spec = this.mTabHost.newTabSpec("Tab3").setIndicator(tabIndicator);
		
		AccountActivity
				.addTab(this, this.mTabHost, spec, (tabInfo = new TabInfo("Tab3",
						AccountFinesFragment.class, args)));
		this.mapTabInfo.put(tabInfo.tag, tabInfo);
		// Default to first tab

		// Apparently required to initialize each tab.

		this.onTabChanged("Tab3");
		this.onTabChanged("Tab2");
		this.onTabChanged("Tab1");
		
		//If a hold notification generated this intent
		
		if(getIntent().getBooleanExtra("showHolds", false)){
			this.onTabChanged("Tab2");
			mTabHost.setCurrentTab(1);
		}

		//
		mTabHost.setOnTabChangedListener(this);
	}

	/**
	 * @param activity
	 * @param tabHost
	 * @param tabSpec
	 * @param clss
	 * @param args
	 */
	private static void addTab(AccountActivity activity, TabHost tabHost,
			TabHost.TabSpec tabSpec, TabInfo tabInfo) {
		// Attach a Tab view factory to the spec
		tabSpec.setContent(activity.new TabFactory(activity));
		String tag = tabSpec.getTag();

		// Check to see if we already have a fragment for this tab, probably
		// from a previously saved state. If so, deactivate it, because our
		// initial state is that a tab isn't shown.
		tabInfo.fragment = activity.getSupportFragmentManager()
				.findFragmentByTag(tag);
		if (tabInfo.fragment != null && !tabInfo.fragment.isDetached()) {
			FragmentTransaction ft = activity.getSupportFragmentManager()
					.beginTransaction();
			ft.detach(tabInfo.fragment);
			ft.commit();
			activity.getSupportFragmentManager().executePendingTransactions();
		}

		tabHost.addTab(tabSpec);
	}

	/**
	 * (non-Javadoc)
	 * 
	 * @see android.widget.TabHost.OnTabChangeListener#onTabChanged(java.lang.String)
	 */
	@Override
	// When the user clicks on a tab, display the appropriate tag.
	public void onTabChanged(String tag) {
		TabInfo newTab = this.mapTabInfo.get(tag);
		System.out.println(tag);
		if (mLastTab != newTab) {
			FragmentTransaction ft = this.getSupportFragmentManager()
					.beginTransaction();
			if (mLastTab != null) {
				if (mLastTab.fragment != null) {
					ft.detach(mLastTab.fragment);
				}
			}
			if (newTab != null) {
				if (newTab.fragment == null) {
					newTab.fragment = Fragment.instantiate(this,
							newTab.clss.getName(), newTab.args);
					ft.add(R.id.realtabcontent, newTab.fragment, newTab.tag);
				} else {
					ft.attach(newTab.fragment);
				}
			}

			mLastTab = newTab;
			ft.commit();
			this.getSupportFragmentManager().executePendingTransactions();
		}
	}

	private class TabInfo {
		private String tag;
		private Class clss;
		private Bundle args;
		private Fragment fragment;

		TabInfo(String tag, Class clazz, Bundle args) {
			this.tag = tag;
			this.clss = clazz;
			this.args = args;
		}

	}

	class TabFactory implements TabContentFactory {

		private final Context mContext;

		/**
		 * @param context
		 */
		public TabFactory(Context context) {
			mContext = context;
		}

		/**
		 * (non-Javadoc)
		 * 
		 * @see android.widget.TabHost.TabContentFactory#createTabContent(java.lang.String)
		 */
		@Override
		public View createTabContent(String tag) {
			View v = new View(mContext);
			v.setMinimumWidth(0);
			v.setMinimumHeight(0);
			return v;
		}

	}


}
